package com.jieshuibao.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jieshuibao.common.req.BaseReq;
import com.jieshuibao.common.res.BaseRes;
import com.jieshuibao.model.db.Attention;
import com.jieshuibao.model.db.AttentionExample;
import com.jieshuibao.model.db.AttentionExample.Criteria;
import com.jieshuibao.model.db.AttentionKey;
import com.jieshuibao.model.db.Duty;
import com.jieshuibao.model.db.RedEnvelopesArticleUser;
import com.jieshuibao.model.db.User;
import com.jieshuibao.model.domain.AttentionArticleUserResponse;
import com.jieshuibao.model.domain.AttentionRequest;
import com.jieshuibao.model.domain.CookieUser;
import com.jieshuibao.model.domain.PagePhone;
import com.jieshuibao.model.domain.PageRequest;
import com.jieshuibao.model.domain.QuestionAdmireResponse;
import com.jieshuibao.service.AttentionService;
import com.jieshuibao.service.CounselorDutyService;
import com.jieshuibao.service.RedisService;
import com.jieshuibao.service.UserService;
import com.jieshuibao.util.StringUtils;

@Controller
@RequestMapping(value = "/attention")
public class AttentionController {
	private static final Logger logger = LoggerFactory
			.getLogger("AttentionController.class");

	@Resource
	private RedisService redisService;

	@Resource
	private UserService userService;

	@Resource
	private AttentionService attentionService;

	@Resource
	private CounselorDutyService counselorDutyService;

	private static final ObjectMapper mapper = new ObjectMapper();

	// 添加关注人 取消关注人
	@RequestMapping(value = "/user", method = RequestMethod.POST)
	@ResponseBody
	public Object addAttention(HttpServletRequest request,
			@RequestBody AttentionRequest attentionRequest) {
		QuestionAdmireResponse questionAdmireResponse = new QuestionAdmireResponse();
		try {
			logger.info("接收：" + mapper.writeValueAsString(attentionRequest));
			
				CookieUser cookieUser = (CookieUser)request.getAttribute("cookieUser");

				if (cookieUser != null) {
					String phoneNum = cookieUser.getPhoneNumber();
					if (phoneNum != null) {

						User user = userService.getUserByPhoneNumber(phoneNum);
						if (user != null) {
							int isAttention = attentionRequest.getIsAttention();
							String phoneNum2 = attentionRequest.getPhoneNum();
							if (phoneNum2 == null || phoneNum2.equals("")) {
								questionAdmireResponse.setCode("3");
								questionAdmireResponse.setDes("数据格式错误");
								return questionAdmireResponse;
							}
							Date date = new Date();

							AttentionExample attentionExample = new AttentionExample();
							Criteria criteria = attentionExample
									.createCriteria();
							criteria.andBeAttentionNumEqualTo(phoneNum2);
							criteria.andAttentionNumEqualTo(phoneNum);
							int i = attentionService
									.countAttention(attentionExample);
							if (isAttention == 1) {
								if (i > 0) {
									// 已关注
									questionAdmireResponse.setCode("1");
									questionAdmireResponse.setDes("关注成功");
								} else {
									Attention attention = new Attention();
									attention.setBeAttentionNum(phoneNum2);
									attention.setAttentionNum(phoneNum);
									attention.setAttentionDate(date);
									attentionService.addAttention(attention);
									questionAdmireResponse.setCode("1");
									questionAdmireResponse.setDes("关注成功");
								}
							} else {
								if (i > 0) {
									AttentionKey attentionKey = new AttentionKey();
									attentionKey.setAttentionNum(phoneNum);
									attentionKey.setBeAttentionNum(phoneNum2);
									attentionService
											.delAttentionByBeAttentionNum(attentionKey);
									questionAdmireResponse.setCode("1");
									questionAdmireResponse.setDes("已取消");
								} else {
									// 已取消
									questionAdmireResponse.setCode("1");
									questionAdmireResponse.setDes("已取消");
								}
							}

						} else {
							questionAdmireResponse.setCode("2");
							questionAdmireResponse.setDes("请重新登录");
						}

					} else {
						// 未登录 登陆时间过期
						questionAdmireResponse.setCode("2");
						questionAdmireResponse.setDes("请重新登录");
					}
				} else {
					// 未登录
					questionAdmireResponse.setCode("2");
					questionAdmireResponse.setDes("请重新登录");
				}

			logger.info("返回："
					+ mapper.writeValueAsString(questionAdmireResponse));
		} catch (Exception e) {
			e.printStackTrace();
			questionAdmireResponse.setCode("0");
			questionAdmireResponse.setDes("系统繁忙请稍后再试！");
		}

		return questionAdmireResponse;
	}

	// 查看所有关注的人
	@RequestMapping(value = "/allUser", method = RequestMethod.POST)
	@ResponseBody
	public Object querryAllAttentionUser(HttpServletRequest request,
			@RequestBody PageRequest pageRequest) {
		AttentionArticleUserResponse attentionArticleUserResponse = new AttentionArticleUserResponse();
		try {

				CookieUser cookieUser = (CookieUser)request.getAttribute("cookieUser");

				if (cookieUser != null) {
					String phoneNum = cookieUser.getPhoneNumber();
					if (phoneNum != null) {
						int maxId = pageRequest.getMaxId();
						int sinceId = pageRequest.getSinceId();
						if (sinceId <= 0) {
							sinceId = 1;
						}
						if (maxId <= 0 || maxId < sinceId) {
							maxId = sinceId;
						}
						User user = userService.getUserByPhoneNumber(phoneNum);
						if (user != null) {
							AttentionExample attentionExample = new AttentionExample();
							attentionExample
									.setOrderByClause("attentionDate desc");
							attentionExample.setPageIndex(sinceId - 1);
							attentionExample.setPageSize(maxId - sinceId + 1);
							Criteria createCriteria = attentionExample
									.createCriteria();
							createCriteria.andAttentionNumEqualTo(phoneNum);
							PagePhone pagePhone = new PagePhone();
							pagePhone.setPageIndex(sinceId);
							pagePhone.setPageSize(maxId);
							pagePhone.setPhoneNum(phoneNum);
							List<RedEnvelopesArticleUser> attentionUsers = attentionService
									.getAttentionUsers(attentionExample);
							if (attentionUsers != null) {
								for (RedEnvelopesArticleUser redEnvelopesArticleUser : attentionUsers) {
									String counselorDuty = redEnvelopesArticleUser
											.getCounselorDuty();
									if (counselorDuty != null
											&& !counselorDuty.equals("")) {
										StringBuilder stringBuilder = new StringBuilder();
										String[] split = counselorDuty
												.split(",");
										if (split != null) {
											for (String ids : split) {
												if (ids != null
														&& !ids.equals("")) {
													Duty duty = counselorDutyService
															.getDutyById(ids);
													if (duty != null) {
														stringBuilder
																.append(duty
																		.getDutyName()
																		+ " ");
													}
												}

											}
											int i = stringBuilder
													.lastIndexOf(" ");
											stringBuilder.delete(i, i + 1);
											redEnvelopesArticleUser
													.setCounselorDuty(stringBuilder
															.toString());
										}
									}
								}

							}

							attentionArticleUserResponse
									.setAttentionUser(attentionUsers);
							attentionArticleUserResponse.setSinceId(sinceId);
							attentionArticleUserResponse.setMaxId(sinceId
									+ attentionUsers.size() - 1);
							attentionArticleUserResponse.setRows(attentionUsers
									.size());
							attentionArticleUserResponse.setCode("1");
						} else {
							attentionArticleUserResponse.setCode("2");
							attentionArticleUserResponse.setDes("请重新登录");
						}

					} else {
						// 未登录 登陆时间过期
						attentionArticleUserResponse.setCode("2");
						attentionArticleUserResponse.setDes("请重新登录");
					}
				} else {
					// 未登录
					attentionArticleUserResponse.setCode("2");
					attentionArticleUserResponse.setDes("请重新登录");
				}

			logger.info("返回："
					+ mapper.writeValueAsString(attentionArticleUserResponse));
		} catch (Exception e) {
			e.printStackTrace();
			attentionArticleUserResponse.setCode("0");
			attentionArticleUserResponse.setDes("系统繁忙请稍后再试！");
		}

		return attentionArticleUserResponse;
	}

	// 我的粉丝
	@RequestMapping(value = "/user/fans", method = RequestMethod.POST)
	@ResponseBody
	public Object querryAllUserFans(HttpServletRequest request,
			@RequestBody BaseReq req) {
		BaseRes<HashMap<String,Object>> res = new BaseRes<HashMap<String,Object>>();
		try {
			HashMap<String,Object> map = new HashMap<String, Object>();
			
			CookieUser cookieUser = (CookieUser) request
					.getAttribute("cookieUser");
			String phoneNum = cookieUser.getPhoneNumber();
			int maxId = req.getMaxId();
			int sinceId = req.getSinceId();
			AttentionExample attentionExample = new AttentionExample();
			attentionExample.setOrderByClause("attentionDate desc");
			attentionExample.setPageIndex(sinceId - 1);
			attentionExample.setPageSize(maxId - sinceId + 1);
			Criteria createCriteria = attentionExample.createCriteria();
			createCriteria.andBeAttentionNumEqualTo(phoneNum);
			
			int countAttention = attentionService.countAttention(attentionExample);
			
			List<RedEnvelopesArticleUser> attentionUsers = attentionService
					.getUserFans(attentionExample);
				for (RedEnvelopesArticleUser redEnvelopesArticleUser : attentionUsers) {
					String counselorDuty = redEnvelopesArticleUser
							.getCounselorDuty();
					if (StringUtils.isNotBlank(counselorDuty)) {
						String counselorDutyName = counselorDutyService
								.getCounselorDutyName(counselorDuty);
						redEnvelopesArticleUser
								.setCounselorDuty(counselorDutyName);
					}
				}
			map.put("fans", attentionUsers);
			map.put("count", countAttention);
			
			res.setData(map);
			res.setSinceId(sinceId);
			res.setMaxId(sinceId + attentionUsers.size() - 1);
			res.setRows(attentionUsers.size());
			res.setCode(BaseRes.SUCCESS_CODE);

			logger.info("返回：" + mapper.writeValueAsString(res));
		} catch (Exception e) {
			e.printStackTrace();
			res.setCode(BaseRes.FAIL_CODE);
			res.setDes(BaseRes.FAIL_DES);
		}

		return res;
	}

}
